package com.rjhch.poi;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

@Slf4j
public class Poi {
    private int rowCount = 100000;
    private int columnCount = 180;
    private String cellValue = "aaaaaaaaaaaaaaaaaaaaaaa";
    private String fileName = "row_" + rowCount + "_column_" + columnCount;

    public void test1() {
        SXSSFWorkbook workbook = new SXSSFWorkbook();
        create_excel(workbook,fileName + "_SXSSFWorkbook_out.xlsx");
    }

    public void test2() {
        XSSFWorkbook workbook = new XSSFWorkbook();
        create_excel(workbook,fileName + "_XSSFWorkbook_out.xlsx");
    }

    private void create_excel(Workbook workbook, String fileName){
        OutputStream outputStream = null;
        try {
            workbook = new XSSFWorkbook();
            workbook.createSheet("aaa");
            Sheet aaa = workbook.getSheetAt(0);
            for (int i = 0; i < rowCount; i++) {
                aaa.createRow(i);
                for (int j = 0; j < columnCount; j++) {
                    aaa.getRow(i).createCell(j).setCellValue(cellValue);
                }

                if ((i + 1) % 1000 == 0){
                    log.info("已创建行数：" + (i + 1));
                }
            }

            log.info("创建excel完成，导出到文件中 。。。");
            outputStream = new FileOutputStream(fileName);
            workbook.write(outputStream);
            log.info("导出到文件中完成 。。。");
        } catch (Exception e) {
            log.error("", e);
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    log.error("", e);
                }
            }
        }
    }

}
